package com.efounder.chat.manager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

import com.efounder.chat.R;
import com.efounder.chat.activity.SecretImageActivity;
import com.efounder.chat.fragment.ChatSenderFragment;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.utils.FileSizeUtil;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.MessagePanSoftUtils;
import com.efounder.pansoft.chat.input.ChatInputView;
import com.efounder.pansoft.chat.photo.JFMessagePicturePickView;
import com.efounder.pansoft.chat.photo.JFPicturePickPhotoWallActivity;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.GlobalLoadingDialog;
import com.utilcode.util.ActivityUtils;
import com.utilcode.util.FileUriUtil;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

import static android.app.Activity.RESULT_OK;
import static com.efounder.chat.activity.GaoDeLocationActivity.LOCATION_RESULT_CODE;
import static com.efounder.chat.activity.SecretFileActivity.SECRET_FILE_RESULT_CODE;

/**
 * 消息发送管理
 *
 * @author YQS
 */
public class ChatMessageSendManager {

    //聊天文件路径
    public static String chatFilePath = ImageUtil.chatpath;

    private Context mContext;
    //当前聊天的人的id
    private int currentChatUserId;
    //当前聊天类型
    private byte chatType;
    private AsyncTask<String, Integer, List<String>> picAsyncTask;
    private ChatSenderFragment.PreSendMessageCallback preSendMessageCallback;


    public ChatMessageSendManager(Context mContext, int currentChatUserId, byte chatType) {
        this.mContext = mContext;
        this.currentChatUserId = currentChatUserId;
        this.chatType = chatType;
    }

    public ChatMessageSendManager(Context mContext) {

        this.mContext = mContext;
    }

    public ChatMessageSendManager setCurrentChatUserId(int currentChatUserId) {
        this.currentChatUserId = currentChatUserId;
        return this;
    }

    public ChatMessageSendManager setChatType(byte chatType) {
        this.chatType = chatType;
        return this;
    }

    public ChatMessageSendManager setPreSendMessageCallback(ChatSenderFragment.PreSendMessageCallback preSendMessageCallback) {
        this.preSendMessageCallback = preSendMessageCallback;
        return this;
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == ChatInputView.REQUEST_CODE_FILE && resultCode == RESULT_OK) {
            //选择文件
            String filePath;
            Uri fileUri = data.getData();
            try {
//                filePath = FileUtil.getPathByUri4kitkat(mContext, fileUri);
                filePath = FileUriUtil.getFilePathByUri(mContext, fileUri);
                File file2 = new File(filePath);
                String autoFileOrFilesSize = FileSizeUtil.getAutoFileOrFilesSize(filePath);
                if (file2.exists()) {
                    MessagePanSoftUtils.sendMsg(filePath, autoFileOrFilesSize, preSendMessageCallback,
                            MessageChildTypeConstant.subtype_file, chatType);
                }
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtil.showToast(AppContext.getInstance(), R.string.wechatview_file_select_fail);
            }
        } else if (resultCode == RESULT_OK && requestCode == ChatInputView.REQUEST_CODE_SELECT_VIDEO) {
            //录制视频完成
            String video_path = data.getStringExtra("path");
            String videoTime = data.getStringExtra("videoTime");
            double fileSize = FileSizeUtil.getFileOrFilesSize(video_path, FileSizeUtil.SIZETYPE_KB);
            if (fileSize < 20) {
                //视频过小，录制失败，不发送消息
                ToastUtil.showToast(mContext.getApplicationContext(), R.string.wechatview_video_record_fail);
                return;
            }
            MessagePanSoftUtils.sendMsg(video_path, videoTime, preSendMessageCallback, MessageChildTypeConstant.subtype_smallVideo, chatType);
        } else if (resultCode == RESULT_OK && data != null && data.getExtras() != null
                && data.getExtras().containsKey(JFPicturePickPhotoWallActivity.SELECTED_VIDEO)) {
            //todo 表示从相册选中了视频 一定要放在下面这个elseif 上面
            String video_path = data.getExtras().getString(JFPicturePickPhotoWallActivity.SELECTED_VIDEO);
            String videoTime = data.getStringExtra("videoTime");
            double fileSize = FileSizeUtil.getFileOrFilesSize(video_path, FileSizeUtil.SIZETYPE_KB);
            if (fileSize < 20) {
                //视频过小，录制失败，不发送消息
                ToastUtil.showToast(mContext.getApplicationContext(), R.string.wechatview_video_record_fail);
                return;
            }
            MessagePanSoftUtils.sendMsg(video_path, videoTime, preSendMessageCallback, MessageChildTypeConstant.subtype_smallVideo, chatType);

        } else if (requestCode == JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE
                && resultCode == RESULT_OK) {
            //图库选择照片
            ArrayList<String> arrayList = (ArrayList<String>) data.getExtras().get("mSelectedPics");
            boolean isRawpic = data.getExtras().getBoolean("isRawPic");
            if (arrayList == null) {
                return;
            }
            sendPicture(arrayList, isRawpic);
            Log.e("RESULT_PICS", arrayList + " " + isRawpic);
        } else if (resultCode == LOCATION_RESULT_CODE) {
            //位置返回的图片以及定位信息
            if (data != null) {
                String imagePath = data.getStringExtra("imagePath");
                String content = data.getStringExtra("content");
                MessagePanSoftUtils.sendMsg(imagePath, content, preSendMessageCallback,
                        MessageChildTypeConstant.subtype_location, chatType);
            }
        } else if (resultCode == SecretImageActivity.SECRET_IMAGE_RESULT_CODE) {
            //发送密图
            if (data != null) {
                List<String> encryptList = (List<String>) data.getExtras().get("encryptList");
                String password = data.getStringExtra("password");
                boolean isRawPic = data.getBooleanExtra("isRawPic", false);
                for (int i = 0; i < encryptList.size(); i++) {
                    Map<String, String> map = new HashMap<>();
                    map.put("password", password);
                    map.put("isRawPic", String.valueOf(isRawPic));
                    JSONObject jsonObject = new JSONObject(map);
                    MessagePanSoftUtils.sendMsg(encryptList.get(i), jsonObject.toString(), preSendMessageCallback,
                            MessageChildTypeConstant.subtype_secret_image, chatType);
                }
            }
        } else if (resultCode == SECRET_FILE_RESULT_CODE) {
            //发送密件
            if (data != null) {
                ArrayList<String> encryptList = (ArrayList<String>) data.getExtras().get("encryptList");
                String password = data.getStringExtra("password");
                for (int i = 0; i < encryptList.size(); i++) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("password", password);
                    JSONObject jsonObject = new JSONObject(map);
                    MessagePanSoftUtils.sendMsg(encryptList.get(i), jsonObject.toString(), preSendMessageCallback,
                            MessageChildTypeConstant.subtype_secret_file, chatType);
                }
            }
        }
    }

    /**
     * 发送图片
     *
     * @param cameraFile
     */
    public void sendPicture(File cameraFile) {
        if (cameraFile != null && cameraFile.exists()) {
            System.out.println(cameraFile.getAbsolutePath());
            String scale = ImageUtil.saveNewImage(cameraFile.getAbsolutePath(), 1280, 1280);
            MessagePanSoftUtils.sendMsg(chatFilePath + ImageUtil.getFileName(chatFilePath + cameraFile.getName())
                    + ".pic", scale, preSendMessageCallback, MessageChildTypeConstant.subtype_image, chatType);
        }
    }

    /**
     * 发送图片
     *
     * @param mSelectPath
     * @param isRawpic
     */
    @SuppressLint("StaticFieldLeak")
    public void sendPicture(final List<String> mSelectPath, final boolean isRawpic) {
        picAsyncTask = new AsyncTask<String, Integer, List<String>>() {
            GlobalLoadingDialog progressDialog = new GlobalLoadingDialog(ActivityUtils.getTopActivity());

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progressDialog.showLoading(ResStringUtil.getString(R.string.common_text_please_wait));

            }

            @Override
            protected List<String> doInBackground(String... params) {
                if (isRawpic) {
                    return mSelectPath;
                }
                List<String> mSelectPath1 = new ArrayList<>();
                for (int i = 0; i < mSelectPath.size(); i++) {
                    System.out.println(mSelectPath.get(i));
                    //如果不是gif动图则进行裁剪压缩
                    if (!ImageUtil.isGifFile((new File(mSelectPath.get(i))))) {
                        ImageUtil.saveNewImage(mSelectPath.get(i), 1280, 1280);
                        mSelectPath1.add(chatFilePath + ImageUtil.getFileName(mSelectPath.get(i)) + ".pic");
                    } else {
                        mSelectPath1.add(mSelectPath.get(i));
                    }
                }
                return mSelectPath1;
            }

            @Override
            protected void onPostExecute(List<String> mSelectPath3) {
                super.onPostExecute(mSelectPath3);
                progressDialog.dismissLoading();
                for (int i = 0; i < mSelectPath3.size(); i++) {
                    String scale = ImageUtil.getPicScale(mSelectPath3.get(i));
                    MessagePanSoftUtils.sendMsg(mSelectPath3.get(i), scale, preSendMessageCallback,
                            MessageChildTypeConstant.subtype_image, chatType);
                }
            }
        };

        picAsyncTask.executeOnExecutor(Executors.newCachedThreadPool());
    }

    /**
     * 发送语音消息
     *
     * @param time
     * @param file
     */
    public void sendVoiceMesage(int time, File file) {

        MessagePanSoftUtils.sendMsg(file.getAbsolutePath(), time + "", preSendMessageCallback,
                MessageChildTypeConstant.subtype_voice, chatType);

    }


    /**
     * 发送语音识别光速短信消息
     *
     * @param content   文本内容
     * @param voicePath 语音文件路径
     */
    public void sendVoiceRecognitionMessage(String content, String voicePath) {
        if (voicePath == null) {
            return;
        }
        HashMap<String, String> property = new HashMap<>();
        if (content == null || "".equals(content)) {
            content = ResStringUtil.getString(R.string.wechatview_voice_text_unidentification);
        }
        property.put("text", content);
        MessagePanSoftUtils.sendMsg(voicePath, new JSONObject(property).toString(), preSendMessageCallback,
                MessageChildTypeConstant.subtype_speechRecognize, chatType);
    }

    public void release() {
        if (picAsyncTask != null) {
            picAsyncTask.cancel(true);
        }
    }
}
